package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.CustomException;
import com.itheima.reggie.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;


    /**
     * 查询所有
     * @return
     */
    @Override
    public List<Category> findAll() {
        //调用mapper查询
      return   categoryMapper.findAll();
    }

    //保存
    @Override
    public void save(Category category) {

        //设置id
        category.setId(IdUtil.getSnowflake(1, 1).nextId());
       /* //设置操作人员
        category.setUpdateUser(1L);
        category.setCreateUser(1L);
        //设置更新时间
        category.setCreateTime(new Date());
        category.setUpdateTime(new Date());*/
        //调用mapper保存
        categoryMapper.save(category);
    }


    //修改
    @Override
    public void update(Category category) {

     /*   //设置修改人和时间
        category.setUpdateUser(1L);
        category.setUpdateTime(new Date());
*/
        //调用mapper保存
        categoryMapper.update(category);
    }


    //删除
    @Override
    public ResultInfo delete(Long id) {
        //根据分类id查询当前菜系下面是否有菜品，有的话返回错误
       Integer num1 =  categoryMapper.countDishByCategoryId(id);

        if (num1 > 0) {
            throw new CustomException("当前分类下有菜品，删除失败！");
        }

        //根据分类id查询当前分类下是否有套餐,如果有,返回错误
       Integer num2 =  categoryMapper.countSetmealByCategoryId(id);
        if (num2 > 0) {
            throw new CustomException("当前分类下有套餐，删除失败！");
        }

        //删除分类
        categoryMapper.delete(id);
        return ResultInfo.success(null);
    }

    //根据type查询分类
    @Override
    public List<Category> findByType(Integer type) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(Category::getType, type);
        return categoryMapper.selectList(wrapper);
    }
}
